package com.gta.edu.sdk.util;

import java.io.Serializable;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

public class EhCacheUtil {
	
	private static CacheManager cacheManager;
	private static Cache cache;
	
	static {
		// 1. 创建缓存管理器
        cacheManager = CacheManager.create(EhCacheUtil.class.getClassLoader().getResourceAsStream("ehcache.xml"));
        // 2. 获取缓存对象
        cache = cacheManager.getCache("userConfirmCache");
	}
	
	private EhCacheUtil() {}
	
	public static void put(String key,String value) {
		Element element = new Element(key, value);
		cache.put(element);
	}
	
	public static Object getObjectValue(String key) {
		Element value = cache.get(key);
		if (value != null) {
			return value.getObjectValue();
		}
		return null;
	}
	
	public static void put(Serializable key,Serializable value) {
		Element element = new Element(key, value);
		cache.put(element);
	}
	
	public static void remove(String key) {
		cache.remove(key);
	}
	
	public static String getValue(String key) {
		Element value = cache.get(key);
		if (value != null) {
			return value.getObjectValue().toString();
		}
		return null;
	}
	
	

	public static void main(String[] args) {
//		// 1. 创建缓存管理器
//        CacheManager cacheManager = CacheManager.create("./src/main/resources/ehcache.xml");
//         
//        // 2. 获取缓存对象
//        Cache cache = cacheManager.getCache("userConfirmCache");
         
        // 3. 创建元素
//        Element element = new Element("key1", "value1");
//         
//        // 4. 将元素添加到缓存
//        cache.put(element);
//         
//        // 5. 获取缓存
//        Element value = cache.get("key1");
		put("aa","123");
        System.out.println("value1: " + getValue("aa"));
//        System.out.println(value.getObjectValue());
        try {
			Thread.sleep(8000);
			System.out.println("value2: " + getValue("aa"));
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        try {
			Thread.sleep(11000);
			System.out.println("value3: " + getValue("aa"));
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
